const Base = require('../../base.js');

module.exports = class extends Base {
  async indexAction() {
    let orderId = this.get('id')
    let userInfo = await this.session('user_info')
    if (!userInfo) return this.fail(-1, '未登录授权')
    let alipaySdk = await think.alipaySdk()
    
    let result
    try {
      result = await alipaySdk.exec('alipay.trade.query', {bizContent: {
        outTradeNo: orderId, // 商品订单ID
      }})
    } catch (e) {}

    let data = { code: -1, msg: '等待支付' }
    if (result.code != '10000') {
      data.msg = '还没有发起支付'
    } else {
      if (result.msg == 'Success') {
        if (result.tradeStatus == 'TRADE_SUCCESS') {
          data = { code: 1, msg: '支付成功' }
          let deal = await this.model('deal/index').deal(orderId)
          console.log('支付成功修改用户状态')
          console.log()
          if (deal.type == 'upgrade') {
            /// 修改用户VIP状态
            await this.model('user/index').edit({
              _id: deal.uid,
              vip: deal._doc.vip
            })
          }
          await this.model('deal/index').setPay(orderId, 1)
        } else {
          data.msg = '等待支付'
        }
      } else {
        data.msg = '订单异常'
      }
    }
    
    this.json({
      status: 200, message: 'success',
      data
    })
  }
};
